<template>
  <van-row>
    <van-nav-bar
      :title="title"
      left-arrow
      left-text="返回"
      @click-left="$emit('close')"
    />
    <van-form ref="submitForm" @submit="doSubmit">
      <van-field
        readonly
        clickable
        name="shipmentDate"
        :value="submitForm.shipmentDate"
        label="日期选择"
        placeholder="点击选择日期"
        input-align="left"
        :rules="[{ required: true, message: '请选择日期' }]"
        @click="showShipmentDate = true"
      />
      <van-field
        v-model="submitForm.customerName"
        readonly
        clickable
        name="customerName"
        label="客户名称"
        placeholder="点击选择客户"
        input-align="left"
        :rules="[{ required: true, message: '请选择客户' }]"
        :disabled="submitForm.id!==''"
        @click="submitForm.id===''?showCustomer=true:false"
      />
      <van-row v-if="submitForm.orderList">
        <van-swipe-cell v-for="(item,index) in submitForm.orderList" :key="index">
          <van-divider content-position="left" :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">{{ `订单${index+1}` }}</van-divider>
          <van-cell-group inset>
            <van-cell title="产品" title-class="cell_value">
              <template #title>
                <div class="title_desc">
                  {{ item.productName }}*{{ item.orderQuantity }}{{ item.unit }}
                </div>
              </template>
              <template #default>
                余数:{{ item.remainingQuantity }}{{ item.unit }}
              </template>
            </van-cell>
            <van-field
              v-model="item.quantity"
              name="送货数量"
              label="本次送货数量"
              type="digit"
              placeholder="(必填)请输入送货数量"
              :rules="[{ validator: checkNumberGreaterThanZero, message: '请填写正确的数量' }]"
              input-align="left"
            />
            <van-field
              v-model="item.remark"
              rows="1"
              autosize
              label="备注"
              type="textarea"
              maxlength="100"
              show-word-limit
              placeholder="请输入备注"
              input-align="left"
            />
          </van-cell-group>
          <template #right>
            <van-button class="swipe_button" square type="danger" text="删除" @click="doDelete(index)" />
          </template>
        </van-swipe-cell>
      </van-row>
      <van-row v-if="submitForm.orderList&&submitForm.orderList.length>0">
        <dict-select
          v-model="submitForm.shipmentType"
          label="送货方式"
          dict-key="shipment_type"
          @input="handleChangeShipmentType"
        />
        <van-field
          v-model="submitForm.recipientName"
          name="recipientName"
          label="收件人名称"
          placeholder="收件人名称"
          input-align="left"
        />
        <van-field
          v-model="submitForm.recipientPhoneNum"
          name="recipientPhoneNum"
          label="收件人手机"
          type="digit"
          placeholder="收件人手机号"
          input-align="left"
        />
        <van-field
          v-model="submitForm.recipientAddress"
          name="recipientAddress"
          label="收件人地址"
          placeholder="收件人地址"
          input-align="left"
        />
        <div v-if="submitForm.shipmentType==='1'||submitForm.shipmentType==='2'">
          <van-field
            v-model="submitForm.carrier"
            name="carrier"
            label="承运商"
            placeholder="请输入承运商/快递/物流公司名称"
            input-align="left"
          />
          <van-field
            v-model="submitForm.trackingNo"
            name="trackingNo"
            label="物流单号"
            placeholder="请输入物流/快递单号"
            input-align="left"
          />
          <van-field
            v-model="submitForm.shipCost"
            name="shipCost"
            label="运费"
            type="number"
            placeholder="请输入运费"
            input-align="left"
          />
        </div>
        <van-field
          v-model="submitForm.remark"
          rows="2"
          autosize
          label="备注"
          type="textarea"
          maxlength="100"
          show-word-limit
          placeholder="备注"
          input-align="left"
        />
      </van-row>
      <van-button style="margin-bottom: 10px" icon="plus" plain block native-type="button" @click="doShowOrder">添加订单</van-button>
      <div style="margin: 16px;">
        <van-button round block type="danger" native-type="submit">提交</van-button>
      </div>
    </van-form>
    <div v-if="showCustomer">
      <select-customer ref="selectCustomer" :visible="showCustomer" @close="handleCloseCustomer" />
    </div>
    <div v-if="showOrder">
      <select-order ref="selectOrder" :visible="showOrder" :disable-ids="submitForm.orderIds" multiple @close="handleCloseOrder" />
    </div>
    <van-calendar v-model="showShipmentDate" :min-date="minDate" :show-confirm="false" @confirm="onConfirmShipmentDate" />
  </van-row>
</template>

<script>
import DictSelect from '@/components/dictSelect.vue'
import SelectCustomer from '@/components/modules/selectCustomer.vue'
import SelectOrder from '@/components/modules/selectOrder.vue'
import { saveShipment, selectShipmentById, updateShipmentById } from '@/api/shipment'
import { Dialog, Toast } from 'vant'
import moment from 'moment'
import Moment from 'moment/moment'

export default {
  name: 'ShipmentSubmitModule',
  components: { SelectOrder, SelectCustomer, DictSelect },
  data() {
    return {
      showShipmentDate: false,
      showCustomer: false,
      showOrder: false,
      title: '',
      submitForm: {},
      minDate: moment(new Date()).subtract(30, 'years').toDate()
    }
  },
  methods: {
    init(id) {
      this.resetForm()
      this.title = '修改送货单'
      if (!id) {
        this.title = '新增送货单'
        return
      }
      selectShipmentById(id).then(resp => {
        if (resp.success) {
          this.submitForm = resp.data
          this.submitForm.orderIds = []
          for (let i = 0; i < this.submitForm.orderList.length; i++) {
            var order = this.submitForm.orderList[i]
            this.submitForm.orderIds.push(order.orderId)
            order.productName = order.orderInfo.productName
            order.orderQuantity = order.orderInfo.quantity
            order.remainingQuantity = order.orderInfo.remainingQuantity
            order.unit = order.orderInfo.unit
          }
        }
      })
    },
    resetForm() {
      this.submitForm = { id: '', customerId: '', orderIds: [] }
    },
    doSubmit() {
      if (this.submitForm.orderList.length === 0) {
        Toast.fail('请选择订单')
        return
      }
      let request = saveShipment
      if (this.submitForm.id) {
        request = updateShipmentById
      }
      request(this.submitForm).then(resp => {
        if (resp.success) {
          this.$toast.success('操作成功')
          this.$emit('close')
        }
      })
    },
    doShowOrder() {
      if (this.submitForm.customerId === '') {
        Toast.fail('请先选择客户')
        return
      }
      this.showOrder = true
      this.$nextTick(() => {
        this.$refs.selectOrder.handleSearch({ customerId: this.submitForm.customerId, shipmentStateList: ['0', '1'] })
      })
    },
    doDelete(index) {
      Dialog.confirm({
        title: '删除订单确认',
        message: '是否从此送货单中移除此订单'
      }).then(() => {
        this.submitForm.orderIds.splice(index, 1)
        this.submitForm.orderList.splice(index, 1)
      })
    },
    onConfirmShipmentDate(row) {
      this.submitForm.shipmentDate = Moment(row).format('YYYY-MM-DD')
      this.showShipmentDate = false
    },
    handleChangeShipmentType(val) {
      this.submitForm.shipmentType = val
    },
    handleCloseCustomer(row) {
      this.showCustomer = false
      if (row) {
        this.submitForm.customerId = row.id
        this.submitForm.customerName = row.customerName
        this.submitForm.recipientName = row.contacts
        this.submitForm.recipientPhoneNum = row.phoneNum
        this.submitForm.recipientAddress = row.address
        this.submitForm.orderList = []
      }
    },
    handleCloseOrder(orderList) {
      this.showOrder = false
      if (orderList && orderList.length > 0) {
        for (let i = 0; i < orderList.length; i++) {
          const row = orderList[i]
          row.orderQuantity = row.quantity
          row.productName = row.productInfo.productName
          row.unit = row.productInfo.unit
          row.quantity = 0
          row.orderId = row.id
          row.remark = ''
          if (this.submitForm.customerId && this.submitForm.customerId !== row.customerId) {
            this.$toast.fail('只能选择相同客户的订单')
            return
          }
          if (this.submitForm.orderIds.length > 0 && this.submitForm.orderIds.indexOf(row.orderId) !== -1) {
            this.$toast.fail(`选择订单与第${this.submitForm.orderIds.indexOf(row.orderId) + 1}条订单重复`)
            return
          }
          this.submitForm.orderIds.push(row.id)
          this.submitForm.orderList.push(row)
        }
      }
    },
    getContainer() {
      return document.body
    },
    checkNumberGreaterThanZero(value) {
      return value > 0
    }
  }
}
</script>

<style scoped>

</style>
